package cn.bugstack.job;

import cn.bugstack.service.IOrderService;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Yuhuan
 * @description
 * @date 2025/8/11 下午5:13
 */

@Slf4j
@Component
public class NoPayNotifyOrderJob {


    @Resource
    private IOrderService orderService;

    @Resource
    private AlipayClient alipayClient;

    @Scheduled(cron = "0/3 * * * * ?")
    public void exec(){
        try{
            log.info("任务：检测未接受到或未正确处理的支付回调通知");
            List<String> orderIds = orderService.queryNoPayNotifyOrder();
            if(null != orderIds || orderIds.isEmpty()){
                return;
            }
            for(String orderId : orderIds){
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel bizModel = new AlipayTradeQueryModel();
                bizModel.setOutTradeNo(orderId);
                request.setBizModel(bizModel);

                AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(request);
                String code = alipayTradeQueryResponse.getCode();

                if ("10000".equals(code)){
                    orderService.changeOrderPaySuccess(orderId);
                }
            }
        }catch(Exception e){
            log.error("检测未接收到或未正确处理的支付回调通知失败",e);
        }

    }

}
